<?php
namespace app\api\controller;

use app\common\model as M;
use service\WechatPayV3Service;

/**
 * 通知模块
 */
class Notify extends \think\Controller
{

    /**
     * 微信支付异步通知
     * @param  [type] $mobile [description]
     * @return [type]         [description]
     */
    public function wechat ()
    {
        $inWechatpaySignature = $this->request->header('Wechatpay-Signature');
        $inWechatpayTimestamp = $this->request->header('Wechatpay-Timestamp');
        $inWechatpaySerial    = $this->request->header('Wechatpay-Serial');
        $inWechatpayNonce     = $this->request->header('Wechatpay-Nonce');
        $inBody               = file_get_contents('php://input');

        $verify = (new WechatPayV3Service)->verifySign($inWechatpaySignature,$inWechatpayTimestamp,$inWechatpaySerial,$inWechatpayNonce,$inBody);
        $params = [
            'verify' => $verify,
            'inWechatpaySignature' => $inWechatpaySignature,
            'inWechatpayTimestamp' => $inWechatpayTimestamp,
            'inWechatpaySerial' => $inWechatpaySerial,
            'inWechatpayNonce' => $inWechatpayNonce,
            'inBody' => $inBody
        ];
        \think\Log::record($params);

        if ( !empty($verify) && is_array($verify) ) {
            $mchid = $verify['mchid'] ?? '';
            $appid = $verify['appid'] ?? '';
            $order_no = $verify['out_trade_no'] ?? '';
            $transaction_id = $verify['transaction_id'] ?? '';

            if ( ($mchid == \think\Env::get('WECHATPAY.MCH_ID')) && ($appid == \think\Env::get('WECHATPAY.APP_ID')) && $transaction_id && $order_no ) {
                M\Order::paySuccess($order_no , $transaction_id);
            }

        }
    }
}//Class End